﻿using System;
using System.Globalization;

namespace Useful.Format
{
    public class FormaterHelper
    {
		// Преобразование строки в число, в не зависимости от типа десятичного разделителя (',', '.')
        public static bool ConvertToDecimal(string str, out decimal res)
        {
            bool isError = false;

            if (!decimal.TryParse(str, out res))
            {
                NumberFormatInfo nfi = (NumberFormatInfo)CultureInfo.CurrentCulture.NumberFormat.Clone();
                nfi.NumberDecimalSeparator = nfi.NumberDecimalSeparator == "," ? "." : ",";

                if (!decimal.TryParse(str, NumberStyles.Currency, nfi, out res))
                    isError = true;
            }

            return !isError;
        }

        public static decimal? ConvertToDecimal(string str, char? numberGroupSeparator, char? numberDecimalSeparator)
        {
            decimal? res = null;

            if (!String.IsNullOrEmpty(str))
            {
                NumberFormatInfo nfp = new NumberFormatInfo();
                nfp.NumberGroupSeparator = numberGroupSeparator != null ? numberGroupSeparator.ToString() : String.Empty;
                nfp.NumberDecimalSeparator = numberDecimalSeparator != null ? numberDecimalSeparator.ToString() : String.Empty;

                decimal d;

                if (decimal.TryParse(str, NumberStyles.Number, nfp, out d))
                    res = d;
            }

            return res;
        }

        public static decimal? ConvertToDecimal(string str, string numberGroupSeparators, string numberDecimalSeparators, char emptyChar)
        {
            decimal? res = null;

            if (!String.IsNullOrEmpty(str))
            {
                str = str.Trim();

                foreach (char gs in numberGroupSeparators)
                {
                    foreach (char ds in numberDecimalSeparators)
                    {
                        res = ConvertToDecimal(str, gs != emptyChar ? (char?)gs : null, ds != emptyChar ? (char?)ds : null);
                        if (res != null)
                            break;
                    }
                    if (res != null)
                        break;
                }
            }

            return res;
        }
    }
}